<template>
  <van-sticky>
    <van-nav-bar
        :title="`至少选一个标签`"
        left-arrow
        @click-left="onClickLeft"
    >
      <template #right>
        <van-icon name="search" size="18"/>
      </template>
    </van-nav-bar>
  </van-sticky>
  <form action="/public">
    <van-search
        v-model="searchText"
        show-action
        placeholder="请输入要搜索的标签"
        @search="onSearch"
        @cancel="onCancel"
    />
  </form>
  <van-divider content-position="left">已选标签</van-divider>
  <div v-if="activeIds.length === 0">请选择您的标签</div>
  <van-row gutter="16" style="padding: 0 16px">
    <van-col>
      <van-tag v-for="tag in activeIds"  closeable size="medium" type="primary" @close="doClose(tag)">
        {{tag}}
      </van-tag>
    </van-col>
  </van-row>
  <van-divider content-position="left">选择标签</van-divider>
  <van-tree-select
      v-model:active-id="activeIds"
      v-model:main-active-index="activeIndex"
      :items="processedTagList"
      @click-item="onClickItem"
  />
  <div style="display: flex; align-items: center">
    <van-button block type="primary" style="margin: 12px" @click="doSearchResult" v-if="!isShow">注册</van-button>
    <van-button block type="primary" style="margin: 12px" @click="editUserTags" v-if="isShow">修改</van-button>
  </div>
</template>

<script setup>
import {onMounted, ref} from 'vue';
import {useRoute, useRouter} from 'vue-router';
import myAxios from "../plugins/myAxios.ts";
import {showToast} from "vant";

const router = useRouter();
const route = useRoute();

const { type } = route.query;
const { userId } = route.query;

const isShow = ref(false);

onMounted(() => {
  console.log(type);
  if (parseInt(type) === 1) {
    isShow.value = true;
  } else {
    isShow.value = false;
  }
});

const searchText = ref('');
let originTagList = [
  {
    text: '年级',
    children: [
      { text: '大一', id: '大一' },
      { text: '大二', id: '大二' },
      { text: '大三', id: '大三' },
      { text: '大四', id: '大四' },
      { text: '研一', id: '研一' },
      { text: '研二', id: '研二' },
      { text: '研三', id: '研三' },
    ],
  },
  {
    text: '主学语言',
    children: [
      { text: 'Java', id: 'java' },
      { text: 'C++', id: 'C++' },
      { text: 'C', id: 'C' },
      { text: 'Go', id: 'go' },
      { text: 'Python', id: 'python' },
      { text: 'JavaScript', id: 'JavaScript' },
      { text: 'TypeScript', id: 'TypeScript' },
    ],
  },
  {
    text: '状态',
    children: [
      { text: '考研', id: '考研' },
      { text: '考公', id: '考公' },
      { text: '找工作', id: '找工作' },
      { text: '实习中', id: '实习中' },
    ],
  },
  {
    text: '性格',
    children: [
      { text: 'i人', id: 'i人' },
      { text: 'e人', id: 'e人' },
      { text: '可i可e', id: '可i可e' },
    ]
  }
];

// 处理原始标签数据，添加父级索引
const processedTagList = ref(originTagList.map((parent, pIndex) => ({
  ...parent,
  children: parent.children.map(child => ({
    ...child,
    parentIndex: pIndex  // 为每个子标签添加父级索引
  }))
})));

// 点击标签项处理函数
const onClickItem = (item) => {
  // 获取当前父级下已选择的标签
  const sameParentTags = activeIds.value.filter(id => {
    const target = findTagById(id);
    return target?.parentIndex === item.parentIndex;
  });

  // 移除同父级已选标签，保留当前点击的标签
  activeIds.value = [
    ...activeIds.value.filter(id => !sameParentTags.includes(id)),
    item.id
  ];
};

// 根据id查找标签详细信息
const findTagById = (id) => {
  for (const parent of processedTagList.value) {
    const found = parent.children.find(child => child.id === id);
    if (found) return found;
  }
  return null;
};

const onSearch = () => {
  processedTagList.value = originTagList.map(parentTag => {
    if (Array.isArray(parentTag.children) && parentTag.children.length > 0) {
      const tempChildren = parentTag.children.filter(item => item.text.includes(searchText.value));
      const tempParentTag = { ...parentTag };
      tempParentTag.children = tempChildren;
      return tempParentTag;
    }
    return parentTag;
  });
};

const onCancel = () => {
  searchText.value = '';
  processedTagList.value = originTagList;
}

// 已选中的标签
const activeIds = ref([]);
const activeIndex = ref(0);

// 一处标签
function doClose(tag) {
  activeIds.value = activeIds.value.filter(item => {
    return item !== tag
  });
}

const { registerUser } = route.query;

const doSearchResult =  async () =>{
  if (activeIds.value.length > 0) {
    const registerUserParam = JSON.parse(registerUser);
    const res = await myAxios.post('/user/register', {
      userAccount: registerUserParam.userAccount,
      userPassword: registerUserParam.userPassword,
      checkPassword: registerUserParam.checkPassword,
      /*
      gender: registerUserParam.gender,
      avatarUrl: registerUserParam.avatarUrl,*/
      username: registerUserParam.username,
      /*    phone: registerUserParam.phone,*/
      tagNameList: activeIds.value,
      longitude: registerUserParam.longitude,
      dimension: registerUserParam.dimension,
    });
    if (res?.code === 0) {
      showToast('注册成功');
      router.push({
        path: '/user/login'
      })
    } else {
      showToast('注册失败' + (`${res.description}` ? `，${res.description}` : ''));
    }
  } else {
    showToast('请至少选择一个标签');
  }
};

const editUserTags = async () => {
  if (activeIds.value.length > 0) {
    const res = await myAxios.post('/user/update', {
      tags: activeIds.value,
      id: parseInt(userId),
    });
    if (res?.code === 0) {
      showToast('修改成功');
      router.back();
    } else {
      showToast('修改失败');
    }
  } else {
    showToast('请至少选择一个标签');
  }

};

const onClickLeft = () => {
  router.back();
}
</script>

<style scoped>

</style>